const id = window.localStorage.getItem("id")
const token = document.querySelector("token")
!id ? window.location.href = "./login.html" : fun()
if (!id){
  window.location.href = "./login.html" 
}
async function fun() {
  const res = await $.ajax({
    url: "http://localhost:8888/cart/list",
    data: { id },
    headers: { "authorization": token }
  })
  if (res.cart.length === 0) {
    $("main>.middle>.none").addClass("active")
    $("main>.middle>.block").removeClass("active")
    return
  }

  let totalNumber = 0, totalSelect = 0, totalPrice = 0
  res.cart.forEach(item => {
    if (item.is_select) {
      totalNumber += item.cart_number
      totalPrice = item.cart_number * item.current_price
      totalSelect++
    }
  })
  let str = `<div class="row">
              <div class="top">
                <div class="col-lg-1">
                  <input type="checkbox" class="select_all" ${totalSelect === res.cart.length ? "checked" : ""}>&emsp;全选
                </div>
                <div class="col-lg-5">
                    商品名称
                </div>
                <div class="col-lg-1">
                    单价
                </div>
                <div class="col-lg-3">
                    数量
                </div>
                <div class="col-lg-1">
                    小计
                </div>
                <div class="col-lg-1">
                    操作
                </div>
            </div>`

  res.cart.forEach(item => {
    str += `
              <div class="middle">
                <div class="col-lg-1">
                <input type="checkbox" class="select_item" data-id=${item.goods_id} ${item.is_select ? "checked" : ""}>&emsp;
                </div>
                <div class="col-lg-5">
                <img src="${item.img_small_logo}">
                <p class="title">${item.title}</p>
                </div>
                <div class="col-lg-1">
                ${item.current_price}元
                </div>
                <div class="col-lg-3">
                <button class="jian" data-id=${item.goods_id} data-num=${item.cart_number}>-</button><input class="input" data-id=${item.goods_id} data-max=${item.goods_number} type="text" value="${item.cart_number}"><button class="jia" data-id=${item.goods_id} data-max=${item.goods_number} data-num=${item.cart_number}>+</button>
                </div>
                <div class="col-lg-1">
                ${(item.cart_number * item.current_price).toFixed(2)}元
                </div>
                <div class="col-lg-1">
                    <i class="iconfont delete" data-id=${item.goods_id}>&#xe641;</i>
                </div>
            </div>`
  })
  str += ` <div class="bottom">
                <div class="col-lg-1 jx">
                    继续购物
                </div>
                <div class="col-lg-1">
                    已选择<span>${totalNumber}</span>件
                </div>
                <div class="col-lg-1 col-lg-offset-7">
                    合计: <span>${totalPrice.toFixed(2)}</span> 元
                </div>
                <button class="col-lg-2 pay ${totalSelect!==0?"active":""}">
                    去结算
                </button>
            </div>
          </div>`

  $(".block").html(str)

}
$(".block")[0].addEventListener("click", async e => {
  if (e.target.className === "select_item") {
    const goodsId = e.target.dataset.id
    const res = await $.ajax({
      url: "http://localhost:8888/cart/select",
      method: "post",
      data: { id, goodsId },
      headers: { "authorization": token }
    })
    if (res.code === 1) fun()
  }
  if (e.target.className === "select_all") {
    const type = +e.target.checked
    const res = await $.ajax({
      url: "http://localhost:8888/cart/select/all",
      method: "post",
      data: {
        id, type
      },
      headers: { authorization: token }
    })
    if (res.code === 1) fun()
  }
  if (e.target.className === "jia") {
    const maxNum = e.target.dataset.maxNum
    const goodsId = e.target.dataset.id
    let number = +e.target.dataset.num
    if (number >= maxNum) return alert("已经到达最大库存")
    const res = await $.ajax({
      url: "http://localhost:8888/cart/number",
      method: "post",
      headers: { "authorization": token },
      data: { id, goodsId, number: ++number }
    })
    if (res.code === 1) fun()
  }
  if (e.target.className === "jian") {
    const goodsId = e.target.dataset.id
    let number = +e.target.dataset.num
    if (number <= 1) return alert("已经最少了")
    const res = await $.ajax({
      url: "http://localhost:8888/cart/number",
      method: "post",
      headers: { "authorization": token },
      data: { id, goodsId, number: --number }
    })
    if (res.code === 1) fun()
  }
  if (e.target.className === "iconfont delete") {
    const goodsId = e.target.dataset.id
    const res = await $.ajax({
      url: "http://localhost:8888/cart/remove",
      data: {
        id, goodsId
      },
      headers: { "authorization": token }
    })
    if (res.code === 1) fun()
  }
  if (e.target.className === "col-lg-2 pay") {
    const res = await $.ajax({
      url: "http://localhost:8888/cart/pay",
      method: "post",
      data: { id },
      dataType: "json",
      headers: { authorization: token }
    })
    if (res.code === 1) alert(res.message)
  }
  if(e.target.className==="col-lg-1 jx"){
    window.location.href="./list.html"
  }
})
$(".none")[0].addEventListener("click",e=>{
  if(e.target.className==="qgw"){
    window.location.href="./list.html"
  }
})

$(".block")[0].addEventListener("keydown", async e => {
  if (e.target.className === "input") {
    if (e.keyCode === 13) {
      const maxNum = e.target.dataset.max
      let value = +e.target.value
      const goodsId = e.target.dataset.id
      let number = parseInt(value)
      if (number <= 0) number = 1
      if (number >= maxNum) number = maxNum
      const res = await $.ajax({
        url: "http://localhost:8888/cart/number",
        method: "post",
        headers: { "authorization": token },
        data: { id, goodsId, number: number }
      })
      if (res.code === 1) fun()
    }
  }
})
$(".block")[0].addEventListener("change", async e => {
  if (e.target.className === "input") {
    const maxNum = e.target.dataset.max
    let value = +e.target.value
    const goodsId = e.target.dataset.id
    let number = parseInt(value)
    if (number >= maxNum) number = maxNum
    if (number <= 0) number = 1
    const res = await $.ajax({
      url: "http://localhost:8888/cart/number",
      method: "post",
      headers: { "authorization": token },
      data: { id, goodsId, number: number }
    })
    if (res.code === 1) fun()
  }
})
$("nav>.row>.col-lg-1>.iconfont").click(function(){
	window.location.href="./index.html"
})
